<script setup>
import { ref, useTemplateRef } from "vue"
import { useStore } from "@/stores/counter";
const store = useStore()

const x = ref(null)
const y = ref(null)
let timer = null;

const title = useTemplateRef("title")
const box = useTemplateRef("box")
const t = document.querySelector('.title')
// 获取鼠标位置和不能超出边框
function move(e) {
  const calculatedX = e.layerX + box.value.clientWidth / 2 - title.value.clientWidth / 2;
  const calculatedY = e.layerY + box.value.clientHeight / 2 - title.value.clientHeight / 2;
  if (calculatedX < box.value.clientWidth - title.value.clientWidth && calculatedX > 0) {
    x.value = calculatedX;
  }
  if (calculatedY < box.value.clientHeight - title.value.clientHeight && calculatedY > 0) {
    y.value = calculatedY
  }
  // 
  //  绝对定位使用
  //  layerX相对于目标 + 事件本身的宽与高 / 2 - 球宽与高的一半 
  //  e.layerX + box.value.clientWidth / 2 - title.value.clientWidth / 2;
}

// 点击进行绘画
function pus() {
  const newDiv = document.createElement("div")
  const style = getComputedStyle(title.value)
  const backgroundColor = style.backgroundColor
  const borderRadius = style.borderRadius
  // 
  newDiv.style.width = title.value.clientWidth + "px"
  newDiv.style.height = title.value.clientHeight + "px"
  newDiv.style.backgroundColor = backgroundColor
  newDiv.style.borderRadius = borderRadius
  newDiv.style.position = "absolute"
  newDiv.style.left = x.value + "px"
  newDiv.style.top = y.value + "px"
  newDiv.style.zIndex = -2
  document.querySelector(".box").appendChild(newDiv)
}
// mousedown  鼠标按下
// mouseup    鼠标按下释法
// mouseleave 鼠标离开边框 

function btn() {
  timer = setInterval(pus, 10);
  console.log(store.count);

}

function btnup() {
  clearInterval(timer);
}

function qk() {
  clearInterval(timer);
}
function qc() {
  const parentElement = document.querySelector('.box');
  const firstChild = parentElement.firstChild; // 获取第一个子元素

  // 循环移除所有子元素，直到只剩下第一个
  while (parentElement.lastChild !== firstChild) {
    parentElement.removeChild(parentElement.lastChild);
  }
}
</script>

<template>

  <div class="box" ref="box" @mousemove.self="move" @mousedown="btn" @mouseup="btnup" @mouseleave="qk">
    <div ref="title" class="title" :style="{ left: x + 'px', top: y + 'px', backgroundColor: store.count }">
    </div>
  </div>
  <button class="hb" @click="qc">清除画板</button>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.box {
  width: 500px;
  height: 500px;
  border: #ccc 1px solid;
  position: relative;
  border-radius: 15px;
}

.box>div {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  position: absolute;
  z-index: -1;
  border: #ccc 2px solid;

}

.hb {
  padding: 3px 10px;
  position: absolute;
  top: -10%;
  left: 50%;
  transform: translate(-50%, 0%);
}
</style>